import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/base/application.dart';
import 'package:panda/entity/good_list_entity.dart';
import 'package:panda/goods/GoodsDetail.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/SignUtil.dart';

import '../base/Constant.dart';

class ZeroGoodsPage extends StatefulWidget {
  int type = 0;
  ZeroGoodsPage({Key key, this.type}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return SelectTopGoodsView();
  }
}

class SelectTopGoodsView extends State<ZeroGoodsPage> {
  List<GoodsListDataData> goodsList = new List();
  int page = 1;
  String group_id = "1";
  String name = "";
  String token = "";
  EasyRefreshController _controller = EasyRefreshController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
      // loadList();
    });
    if (APPLIC.userInfoMap != null)
      group_id = APPLIC.userInfoMap['user_msg']['group_id'].toString();
    loadList();
  }

  loadList() async {
    Map map = new Map();
    map['goods_name'] = name;
    map['p'] = page.toString();
    map['per'] = "10";
    map['cat_id'] = "6";
    map['sign_type'] = SignType.GET_GOODS_LIST;
    Response<String> response =
        await HttpUtil().post(Api.GET_GOODS_LIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    if (userMap['code'] == 1 && mounted) {
      GoodsListEntity bannerEntity = new GoodsListEntity.fromJson(userMap);
      setState(() {
        if (page == 1) {
          goodsList.clear();
        }
        if (page == 1) {
          _controller.resetLoadState();
          _controller.finishRefresh();
        } else {
          _controller.finishLoad(
              success: true, noMore: bannerEntity.data.datas.length == 0);
          if (bannerEntity.data.datas.length == 0) {
            Fluttertoast.showToast(msg: "已加载全部");
          }
        }
        goodsList.addAll(bannerEntity.data.datas);
        setState(() {});
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return new Scaffold(
      // appBar: new AppBar(
      //   title: Text(widget.type == 1 ? "0元购" : '熊猫自营',
      //       style: TextStyle(
      //           fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
      //           color: Colors.white)),
      //   backgroundColor: mainColor,
      //   brightness: Brightness.light,
      //   centerTitle: true,
      //   iconTheme: new IconThemeData(color: Colors.white),
      //   elevation: 0.5,
      // ),
      backgroundColor: mainColor,
      body: new Container(
        margin: EdgeInsets.only(
            top:
                ScreenUtil.getInstance().setHeight(kBottomNavigationBarHeight)),
        decoration: BoxDecoration(
            color: mainColor,
            image: DecorationImage(
                image: AssetImage("images/bg_send.png"), fit: BoxFit.fill)),
        width: MediaQuery.of(context).size.width,
        // padding: EdgeInsets.only(top: ScreenUtil.getInstance().setHeight(270)),
        // color: white,
        alignment: Alignment.centerLeft,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            GestureDetector(
              child: Padding(
                padding: EdgeInsets.all(15),
                child: Icon(
                  Icons.arrow_back_ios,
                  color: white,
                ),
              ),
              onTap: () {
                Navigator.of(context).pop();
              },
              behavior: HitTestBehavior.opaque,
            ),
            Container(height:ScreenUtil.getInstance().setHeight(160)),
            Expanded(
                child: new EasyRefresh(
              enableControlFinishRefresh: true,
              enableControlFinishLoad: true,
              header: MaterialHeader(),
              footer: MaterialFooter(),
              controller: _controller,
              child: ListView.builder(
                  itemBuilder: _renderRow,
                  itemCount: goodsList.length),
              onRefresh: () async {
                page = 1;
                loadList();
              },
              onLoad: () async {
                page++;
                loadList();
              },
            ))
          ],
        ),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    return GestureDetector(
      child: Container(
        margin: EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setHeight(DP_20),
            ScreenUtil.getInstance().setHeight(DP_20),
            ScreenUtil.getInstance().setHeight(DP_20),
            0),
        // padding: EdgeInsets.all(10),
        decoration: BoxDecoration(
            color: white,
            borderRadius: BorderRadius.circular(
                ScreenUtil.getInstance().setHeight(DP_10))),
        child: Material(
          borderRadius:
              BorderRadius.circular(ScreenUtil.getInstance().setHeight(DP_10)),
          color: white,
          child: new Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Stack(
                children: <Widget>[
                  ClipRRect(
                    borderRadius: BorderRadius.only(
                        bottomLeft: Radius.circular(
                            ScreenUtil.getInstance().setHeight(DP_10)),
                        topLeft: Radius.circular(
                            ScreenUtil.getInstance().setHeight(DP_10))),
                    child: CachedNetworkImage(
                        imageUrl: Api.ImgBaseUrl + goodsList[index].img,
                        width: ScreenUtil.getInstance().setHeight(160),
                        fit: BoxFit.fill,
                        height: ScreenUtil.getInstance().setHeight(160)),
                  ),
                  Offstage(
                    child: Container(
                        alignment: Alignment.center,
                        child: Text(
                          '已售罄',
                          style: TextStyle(color: white, fontSize: 17),
                        ),
                        color: Color.fromARGB(125, 0, 0, 0),
                        width: ScreenUtil.getInstance().setHeight(160),
                        height: ScreenUtil.getInstance().setHeight(160)),
                    offstage: (int.parse(goodsList[index].sales_volume) +
                                int.parse(goodsList[index].virtual_volume)) >=
                            int.parse(goodsList[index].num)
                        ? false
                        : true,
                  )
                ],
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    Padding(
                      padding: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setHeight(DP_15),
                          ScreenUtil.getInstance().setHeight(DP_15),
                          ScreenUtil.getInstance().setHeight(DP_15),
                          ScreenUtil.getInstance().setHeight(DP_8)),
                      child: Text(
                        goodsList[index].goods_name,
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: black),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setHeight(DP_15),
                          ScreenUtil.getInstance().setHeight(5),
                          ScreenUtil.getInstance().setHeight(DP_15),
                          ScreenUtil.getInstance().setHeight(5)),
                      child: Text("已售: " + (int.parse(goodsList[index].sales_volume) +
                              int.parse(goodsList[index].virtual_volume)).toString(),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE-6),
                            color: black_99)),
                    ),
                    Row(children: <Widget>[
                      Expanded(
                          child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: <Widget>[
                            Padding(
                              padding: EdgeInsets.fromLTRB(
                                  ScreenUtil.getInstance().setHeight(DP_15),
                                  0,
                                  ScreenUtil.getInstance().setHeight(DP_15),
                                  ScreenUtil.getInstance().setHeight(DP_15)),
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: <Widget>[
                                  Text('活动价:  ' + MONEY,
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(MINI_FONT_SIZE + 4),
                                          color: black)),
                                  Text("0 ",
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(NORMAL_FONT_SIZE + 25),
                                          color: black)),
                                  Text(
                                      '市场价:' +
                                          MONEY +
                                          goodsList[index].old_price.toString(),
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                          decoration:
                                              TextDecoration.lineThrough,
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(MINI_FONT_SIZE + 2),
                                          color: black_99)),
                                ],
                              ),
                            ),
                          ])),
                      new Container(
                        height: ScreenUtil.getInstance().setWidth(DP_40),
                        margin: EdgeInsets.only(right: 10),
                        alignment: Alignment.center,
                        // width: ScreenUtil.getInstance().setWidth(DP_160),
                        decoration: new BoxDecoration(
                            color: mainColor,
                            borderRadius: BorderRadius.only(
                                bottomLeft: Radius.circular(3),
                                bottomRight: Radius.circular(3))),
                        child: new Padding(
                          padding: EdgeInsets.only(left: 10.0, right: DP_10),
                          child: new Text(
                            "立即购买",
                            style: new TextStyle(
                                color: Colors.white,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE - 2)),
                          ),
                        ),
                      )
                    ])
                  ],
                ),
              )
            ],
          ),
        ),
      ),
      onTap: () {
        if ((int.parse(goodsList[index].sales_volume) +
                int.parse(goodsList[index].virtual_volume)) >=
            int.parse(goodsList[index].num)) {
          Fluttertoast.showToast(msg: '亲宝贝已经售馨，下次早抢哦！');

          return;
        }
        Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
          return GoodsDetailPage(
            goods_id: goodsList[index].goods_id,
            img: goodsList[index].img,
            zero:"1"
          );
        }));
      },
    );
  }

  buildAvatar(List<GoodsListDataDatasTag> avatars) {
    List<Widget> list = new List();
    list.add(ClipOval(
      child: CachedNetworkImage(
          imageUrl: Api.ImgBaseUrl + avatars[0].avatar,
          width: ScreenUtil.getInstance().setHeight(35),
          height: ScreenUtil.getInstance().setHeight(35)),
    ));
    for (int i = 1; i < avatars.length; i++) {
      list.add(
        Positioned(
          left: ScreenUtil.getInstance().setHeight(25) * i.toDouble(),
          child: ClipOval(
            child: CachedNetworkImage(
                imageUrl: Api.ImgBaseUrl + avatars[i].avatar,
                width: ScreenUtil.getInstance().setHeight(35),
                height: ScreenUtil.getInstance().setHeight(35)),
          ),
        ),
      );
    }
    return list;
  }
}
